// #include <string>

#include "../code/TcpServer.h"
#include "../code/utility/Logger.h"

class EchoServer
{
public:
    EchoServer(EventLoop *loop,
               const InetAddress &addr,
               TcpServer::ListenOption opt,
               const std::string &name)
        : loop_(loop), server_(loop, addr, opt, name)
    {
        // 注册回调
        this->server_.setConnectionCallback(
            std::bind(&EchoServer::onConnection, this, std::placeholders::_1));

        this->server_.setReadWriteCallback(
            std::bind(&EchoServer::onReadWrite, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));

        // 设置合适的subloop线程数量
        this->server_.setThreadNum(3);
    }

    void start()
    {
        this->server_.start();
    }

private:
    // 连接建立或断开回调
    void onConnection(const TcpConnectionPtr &conn)
    {
        if (conn->isConnected())
        {
            LOG_INFO("Connection UP : %s", conn->getPeerAddr().toIpPort().c_str());
        }
        else
        {
            LOG_INFO("Connection DOWN : %s", conn->getPeerAddr().toIpPort().c_str());
        }
    }

    // 可读写事件回调
    void onReadWrite(const TcpConnectionPtr &conn, Buffer *buf, Timestamp time)
    {
        std::string msg = buf->getAllReadableData();
        conn->sendData(msg);
        // conn->shutdown();    // 写半关闭，底层响应EPOLLHUP，一般执行closeCallback_
    }

    EventLoop *loop_;
    TcpServer server_;
};

int main()
{
    EventLoop loop{};
    InetAddress addr(8633);

    // 初始化注册回调等
    EchoServer server(&loop, addr, TcpServer::ListenOption::ReusePort, "EchoServer");

    // threadPool_、Acceptor::listen()
    // acceptSocket_.listen()、acceptChannel_.enableReadEvent()
    server.start();
    loop.start(); // poller_->poll()

    return 0;
}